package com.acme.bankapp.domain.bank;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.acme.bankapp.domain.exceptions.ClientExistsException;
import com.acme.bankapp.service.bank.ClientRegistrationListener;

public class Bank implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	private int numOfClients;	
	transient private int maxNumListener = 2;
	private HashSet <Client> clients;
	transient private ClientRegistrationListener [] listeners;
	
	public Bank() {
		numOfClients = 0;	
		clients = new HashSet <Client> ();
		listeners = new ClientRegistrationListener[maxNumListener];	
		
		listeners[0] = new ClientRegistrationListener() {		   
			   
			public void onClientAdded(Client c) {
			   System.out.println(c);
			}
		 };	
			   
		 listeners[1] = new ClientRegistrationListener() {
					   
			  public void onClientAdded(Client c) {
					System.out.println("Notification email for client " + c.getClientSalutation() +
				" to be sent");
			  }		
		};	
	}
	
	public int getNumClients() {
		return numOfClients;
	}
	
	public Set<Client> getClients () {
		
		return Collections.unmodifiableSet(clients);
	}	
	
	public Client getClient() {
		Iterator<Client> iter = clients.iterator();
		return iter.next();
	}
	
	public void addClient (Client client) throws ClientExistsException {
			
		if(!clients.add(client)) {
			throw new ClientExistsException("this client already exists");
		}
				
		for (int i = 0; i < maxNumListener; i++) {
			listeners[i].onClientAdded(client);
		}			
		numOfClients++;
	}

	@Override
	public String toString() {
		return clients.toString();
	}
	
}
